package com.wan.net.core.client;

import com.wan.core.shutdown.ShutdownManager;
import com.wan.net.config.HostAndPort;
import com.wan.net.core.AbstractServer;
import com.wan.net.core.packet.Packet;
import com.wan.net.session.AttributeKeys;
import com.wan.util.Constants;
import com.wan.util.cglib.FastClassUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public abstract class AbstractClient implements Client {
    protected static final Logger logger = LoggerFactory.getLogger(AbstractClient.class);
    protected static final int IDLE_TIMEOUT = 180;

    protected static final EventLoopGroup nioEventLoopGroup = Epoll.isAvailable()
            ? new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1, new DefaultThreadFactory("netty-client", true))
            : new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1, new DefaultThreadFactory("netty-client", true));
    static {
        ShutdownManager.addShutdown(AbstractClient::shutdown);
    }

    protected final HostAndPort hostAndPort;
    protected Bootstrap bootstrap;
    protected Channel channel;
    // 空闲超时时间（秒）
    protected final int idleTimeout;
    protected final ChannelHandler channelHandler;

    public AbstractClient(HostAndPort host) {
        this(host,IDLE_TIMEOUT,null);
    }

    public AbstractClient(HostAndPort hostAndPort,@Nullable ChannelHandler channelHandler){
        this(hostAndPort,IDLE_TIMEOUT,channelHandler);
    }

    public AbstractClient(HostAndPort hostAndPort,int idleTimeout){
        this(hostAndPort,idleTimeout,null);
    }

    public AbstractClient(HostAndPort hostAndPort,int idleTimeout, @Nullable ChannelHandler channelHandler) {
        this.hostAndPort = hostAndPort;
        this.idleTimeout = idleTimeout;
        if(channelHandler == null){
            channelHandler = FastClassUtil.newInstance(getClientType().getAssignHandler());
        }
        this.channelHandler = channelHandler;
        ClientFactory.add(this);
    }

    protected abstract void channelChannelInitializer(ChannelPipeline pipeline);

    /**
     * 客户端可允许重复open，重连
     */
    @Override
    public synchronized void open() {
        this.bootstrap = new Bootstrap();
        this.bootstrap.group(nioEventLoopGroup)
                .channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(16 * Constants.BYTE_OF_KB, 16 * Constants.BYTE_OF_MB))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new IdleStateHandler(0,0,idleTimeout));
                        channelChannelInitializer(pipeline);
                        pipeline.addLast(channelHandler);
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(hostAndPort.getHost(), hostAndPort.getPort());
        channelFuture.syncUninterruptibly();

        if (channelFuture.isSuccess()) {
            if (channelFuture.channel().isActive()) {
                channel = channelFuture.channel();
                logger.info("{} client is ready, waiting for activate",getClientType().name().toLowerCase());
                CountDownLatch latch = AttributeKeys.getOrSet(channel,AttributeKeys.SIGNAL,()->new CountDownLatch(1));
                try {
                    if(latch.await(1500, TimeUnit.MILLISECONDS)){
                        logger.info("{} client connected to [{}] success",getClientType().name().toLowerCase(), getTargetRemote());
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } else if (channelFuture.cause() != null) {
            logger.error("启动客户端失败",channelFuture.cause());
        } else {
            logger.error("启动客户端[client:{}]未知错误", this);
        }
    }

    public abstract ClientType getClientType();

    @Override
    public synchronized void close(){
        try {
            if(channel != null) channel.close();
            ClientFactory.remove(this);
        }catch (Exception e){
            logger.error("{} client close error",getClientType().name().toLowerCase(),e);
        }
    }

    public boolean isActive(){
        boolean active = channel != null && channel.isActive();
        if(!active) {
            synchronized (this) {
                active = channel != null && channel.isActive();
                if (!active) {
                    logger.warn("客户端[{}]连接失效，需要重连,target:{}", getClientType().name().toLowerCase(), hostAndPort);
                    onInactive();
                }
            }
        }
        return channel != null && channel.isActive();
    }

    @Override
    public void send(Packet packet) {
        if(isActive()){
            channel.writeAndFlush(packet);
            return;
        }
        logger.warn("消息发送失败,target:{},cmd:{}",hostAndPort,packet.getMessageId());
    }

    /**
     * 连接不活跃时，是否需要操作和重连
     */
    protected abstract void onInactive();

    @Override
    public HostAndPort getTargetRemote() {
        return hostAndPort;
    }

    public synchronized static void shutdown() {
        AbstractServer.shutdownEventLoopGracefully(nioEventLoopGroup);
    }

}
